<?php
/**
 * Description of user
 *
 * @author dmitryy
 */
class Models_User extends Access_Db {
    function validate($user) //validating user data while register
    {
        if(isset($user['submit']))
        {
            $errors = array();
            //checking username
            if(!preg_match("/^[a-zA-Z0-9]+$/",$user['0']))
            {
                $errors[] = "Username can only consist of letters of the alphabet and numbers.";
            }
            if(strlen($user['0']) < 3 or strlen($user['0']) > 30)
            {
                $errors[] = "Username must be at least 3 characters and no more than 30.";
            }
            //check to see whether the user exists by that name
            $select = array(
                'id',
                'login'
                );
            $table = 'users';
            $where = "login='" . $user['0'] . "'";
            $this->select($select, $table, $where);
            $row = $this->getSelected();
            if($row)
            {
                $errors[] = "This username already exists in the database.";
            }
            return $errors;
        }
        return FALSE;
    }
    
    function addNewUser($user)
    {
        $login = $user['0'];
        $password = md5(md5(trim($user['1'])));
        $query = "INSERT INTO users (login, md5_password) VALUES (?, ?)";
        $this->prepare($query);
        $this->insert(array($login, $password));
        $id = $this->getLAstInsertedID();
        $userId = array($this->getLAstInsertedID());
        $query = "INSERT INTO user_roles (user_id) VALUES (?)";
        $this->prepare($query);
        $this->insert($userId);
        $query = "INSERT INTO users_data (user_id) VALUES (?)";
        $this->prepare($query);
        $this->insert($userId);
        $query = "INSERT INTO roles (name, type) VALUES (?,?)";
        $this->prepare($query);
        $data = array($login,'1');
        $this->insert($data);
        $roleId = $this->getLAstInsertedID();
        $query = "INSERT INTO user_roles (user_id, role_id) VALUES (?,?)";
        $data = array($userId['0'], $roleId);
        $this->prepare($query);
        $this->insert($data);
        $query = "INSERT INTO role_permissions (role_id, article_id, action, controller) VALUES (?,?,?,?)";
        $permissionArr = array(
            '4',
            $id,
            'activateuser',
            'admin'
        );
        $this->prepare($query);
        $this->insert($permissionArr);
        return TRUE;
    }
    
    function getUserData($id)
    {
        $select = array(
            'id',
            'first_name',
            'second_name',
            'email',
            'skype',
            'icq',
            'info'
        );
        $from = 'users_data';
        $where = "user_id='$id'";
        $this->select($select, $from, $where);
        return $this->getSelected();
    }

    function generateCode($length=6) //generate random string
    {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHI JKLMNOPRQSTUVWXYZ0123456789";
        $code = "";
        $clen = strlen($chars) - 1;  
        while (strlen($code) < $length) 
        {
                $code .= $chars[mt_rand(0,$clen)];  
        }
        return $code;
    }
    
    function auth($arr) //authorithation user in site 
    {
        if(isset($arr['submit_login']))
        {
            $select = array(
                'id',
                'login',
                'md5_password'
            );
            $table = 'users';
            $where = "login='" . $arr['login'] . "'";
            $this->select($select, $table, $where);
            $user = $this->getSelected();
            if(($user['login'] === $arr['login']) and ($user['md5_password'] === md5(md5($arr['password']))))
            {
                $hash = $this->generateCode();
                $query = "UPDATE users SET hash='$hash' WHERE id='" . $user['id'] . "'";
                $this->execQuery($query);
                setcookie("hash", $hash, time()+60*60*24*30);                   //<<hash
                setcookie("user_id", $user['id'], time()+60*60*24*30);          //<<user id
                setcookie("login", $user['login'], time()+60*60*24*30);         //<<user login
                header("Location: /user"); 
                return TRUE;
            } else {
                header("Location: /user/error");
                return FALSE;
            }
        }
    }
    
    function out() //destroy user session
    {
        setcookie("hash", '', time()-60*60*24*30);                   
        setcookie("user_id", '', time()-60*60*24*30);          
        setcookie("login", '', time()-60*60*24*30);   
        header("Location: /"); 
    }
    
    function isAuth() //check session and coocie
    {
        if(isset($_COOKIE['user_id']) & isset($_COOKIE['hash']))
        {
            $select = array(
                'id',
                'login',
                'hash'
            );
            $table = 'users';
            $where = "id='" . $_COOKIE['user_id'] . "'" ;
            $this->select($select, $table, $where);
            $user = $this->getSelected();
            if($_COOKIE['hash'] !== $user['hash'])
            {
                return FALSE;
                $this->out();
            }
            return TRUE;
        }
    }
    
    function getNewUsersCount()
    {
        $select = array(
            'count(id)'
        );
        $from = "users";
        $where = "active='0'";
        $this->select($select, $from, $where);
        return $this->getSelected();
    }
    
    function setActiveUser($id)
    {
        $query = "UPDATE users SET active='1' where id='$id'";
        $this->execQuery($query);
        $query = "INSERT INTO user_roles (user_id, role_id) VALUES ('$id', '2')"; //IMPORTANT: 2 - id of the role 'user', may be another (!!!)
        $this->execQuery($query);
    }
    
    function removeUser($id)
    {
        //TODO
    }

    function getNewUsers()
    {
        $select = array(
            'id',
            'login'
        );
        $from = 'users';
        $where = "active='0'";
        $this->select($select, $from, $where);
        $result = array();
        while($row = $this->getSelected())
        {
            $result[] = $row;
        }
        return $result;
    }
    
    function getUserRoles($id)
    {
        $select = array(
            'id',
            'role_id'
        );
        $from = 'user_roles';
        $where = "user_id='$id'";
        $this->select($select, $from, $where);
        $userRoles = array();
        while($row = $this->getSelected())
        {
            $userRoles[] = $row;
        }
        $select = array(
            'id',
            'name'
        );
        $from = 'roles';
        $rowEx = array();
        foreach ($userRoles as $roles)
        {
            $where = "id='" . $roles['role_id'] . "'";
            $this->select($select, $from, $where);
            $rowEx[] = $this->getSelected();
        }
        return $rowEx;
    }
    
    function getOwner($item,$userId)
    {
        switch ($item){
            case 'article' :
                $table = $this->lang . '_articles';
                break;
            case 'subarticle' :
                $table = $this->lang . '_sub_articles';
                break;
            case 'anonce' :
                $table = $this->lang . '_anonces';
                break;
            default :
                return FALSE;
                break;
        }
        $where = "user_id='$userId'";
        $select = array(
            'id'
        );
        $this->select($select, $table, $where);
        $result = array();
        while ($row = $this->getSelected())
        {
            $result[] = $row;
        }
        return $result;
    }
    
    function isEditable($id, $userId)
    {
        //TODO
        switch ($item){
            case 'article' :
                $action = 'edit';
                $controller = 'articles';
                break;
            case 'subarticle' :
                $action = 'editsub';
                $controller = 'articles';
                break;
            case 'anonce' :
                $action = 'editanonce';
                $controller = 'articles';
                break;
            default :
                return FALSE;
                break;
        }
        $select = array(
            'id',
            'action',
            'controller',
            'article_id',
            'role_id'
        );
        $from = 'role_permissions';
        $where = "article_id='$id', action='$action', controller='$controller'";
        $this->select($select, $from, $where);
        $result = array();
        while ($row = $this->getSelected())
        {
            $result[] = $row;
        }
        return $result;
    }

    function recoverPassword($id)
    {
        //TODO
    }
    
    function getAllUsers()
    {
        $select = array(
            'id',
            'login'
        );
        $from = 'users';
        $where = "1";
        $this->select($select, $from, $where);
        $result = array();
        while($row = $this->getSelected())
        {
            $result[] = $row;
        }
        return $result;
    }
    
    function validateRole($arr)
    {
        $errors = array();
        if(($arr['0'] == '') or ($arr['0'] == ' '))
        {
            $errors[] = "Fieald is empty.";
            return $errors;
        }
        return FALSE;
    }

    function setRole($arr)
    {
        $query = "INSERT INTO roles (name) VALUES (?)";
        $this->prepare($query);
        $this->insert($arr);
        $id = $this->getLAstInsertedID();
        $query = "insert into role_permissions (role_id, article_id, action, controller) VALUES (?,?,?,?)";
        $arrPermission = array(
            '4', // 4 - is a id of the admin role !!!!!!!!!
            $id,
            'permissions',
            'admin'
        );
        $this->prepare($query);
        $this->insert($arrPermission);
    }
    
    function getAllRoles()
    {
        $select = array('id','name');
        $from = 'roles';
        $this->select($select, $from);
        $result = array();
        while($row = $this->getSelected())
        {
            $result[] = $row;
        }
        return $result;
    }
    
    function getAllActions()
    {
        $select = array(
            'DISTINCT action'
        );
        $from = 'role_permissions';
        $this->select($select, $from);
        $result = array();
        while ($row = $this->getSelected())
        {
            $result[] = $row;
        }
        return $result;
    }
    
    function getAllControllers()
    {
        $select = array(
            'DISTINCT controller'
        );
        $from = 'role_permissions';
        $this->select($select, $from);
        $result = array();
        while ($row = $this->getSelected())
        {
            $result[] = $row;
        }
        return $result;
    }
    
    function getRolesDataByArticle($id)
    {
        $select = array(
            'role_permissions.role_id',
            'role_permissions.action',
            'role_permissions..controller',
            'roles.name'
        );
        
    }
}